<template>
    <div class="main">
        <div class="head-wrap flex-jsb">
            <div class="flex">
                <el-form :model="form" :inline="true" ref="form" label-width="100px" class="form">
                    <el-form-item label="库房名称：" prop="resourceId">
                        <el-select size="mini" v-model="form.resourceId" placeholder="请选择操作类型" @focus="handleFocus"
                            @blur="handleBlur">
                            <el-option :label="item.title" :value="item.resourceId" :key="item.resourceId"
                                v-for="item in selecData" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <div v-if="robotStatusData && robotStatusData.status"
                    style="display: flex;align-items: center;font-weight: bold;color: #4dc5a9;">
                    {{
                        `提示：当前机器人正在巡检，已配置${robotStatusData.allCount}个预置位，当前巡检第${robotStatusData.current}个预置位，还剩${robotStatusData.residue}个预置位。`
                    }}
                </div>
            </div>
            <div>
                <el-button size="mini" type="primary" @click="handleResourceChange">切换</el-button>
                <el-button size="mini" type="primary" @click="goBack">返回</el-button>
            </div>
        </div>
        <div class="bottom-wrap mt15">
            <div class="table-wrap mt15">
                <el-row :gutter="10" ref="videoWrap">
                    <el-col :lg="16" :xl="18" ref="videoHome">
                        <monitorVideo ref="monitorVideoRef" :width="`${offsetWidth}px`" height="76vh"
                            code="44030500581314000014" :config="configData" />
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-card
                            :body-style="{ 'display': 'flex', 'flex-direction': 'row', 'justify-content': 'space-between' }">
                            <div slot="header">
                                <span>摄像头控制</span>
                            </div>
                            <div class="circle">
                                <div class="inner-circle">
                                    <i v-for="item in 8" :key="item" class="el-icon-caret-top"
                                        :class="`inner-circle-${item}`" @mousedown="mouseDownPTZControl(item)"
                                        @mouseup="mouseUpPTZControl()"></i>
                                    <div class="inner-btn" @click.stop="mouseDownPTZControl(9)">
                                        <i class="el-icon-refresh"></i>
                                    </div>
                                </div>
                            </div>
                            <div class="robot-control">
                                <div class="robot-control-item">
                                    <span>调焦：</span>
                                    <div>
                                        <el-button size="mini" type="primary"
                                            @mousedown.native="$refs.monitorVideoRef.PTZZoomIn()"
                                            @mouseup.native="$refs.monitorVideoRef.PTZZoomStop()">调焦+</el-button>
                                        <el-button size="mini" type="primary"
                                            @mousedown.native="$refs.monitorVideoRef.PTZZoomout()"
                                            @mouseup.native="$refs.monitorVideoRef.PTZZoomStop()">调焦-</el-button>
                                    </div>
                                </div>
                                <div class="robot-control-item">
                                    <span>聚焦：</span>
                                    <div>
                                        <el-button size="mini" type="primary"
                                            @mousedown.native="$refs.monitorVideoRef.PTZFocusIn()"
                                            @mouseup.native="$refs.monitorVideoRef.PTZFoucusStop()">聚焦+</el-button>
                                        <el-button size="mini" type="primary"
                                            @mousedown.native="$refs.monitorVideoRef.PTZFoucusOut()"
                                            @mouseup.native="$refs.monitorVideoRef.PTZFoucusStop()">聚焦-</el-button>
                                    </div>
                                </div>
                                <div class="robot-control-item">
                                    <span>光圈：</span>
                                    <div>
                                        <el-button size="mini" type="primary"
                                            @mousedown.native="$refs.monitorVideoRef.PTZIrisIn()"
                                            @mouseup.native="$refs.monitorVideoRef.PTZIrisStop()">光圈+</el-button>
                                        <el-button size="mini" type="primary"
                                            @mousedown.native="$refs.monitorVideoRef.PTZIrisOut()"
                                            @mouseup.native="$refs.monitorVideoRef.PTZIrisStop()">光圈-</el-button>
                                    </div>
                                </div>
                            </div>
                        </el-card>
                        <el-card style="margin-top: 10px;">
                            <div slot="header">
                                <span>机器人控制</span>
                            </div>
                            <div class="circle2">
                                <div class="inner-circle">
                                    <i v-for="item in 4" :key="item" class="el-icon-caret-top"
                                        :class="`inner-circle-${item}`" @mousedown="handleKeyDown(item)"
                                        @mouseup="handleKeyUp(item)"></i>
                                </div>
                            </div>
                        </el-card>
                        <el-card style="margin-top: 10px;">
                            <div slot="header">
                                <div class="flex-jsb">
                                    <span>预置位</span>
                                    <el-button size="mini" type="primary" @click="handleAdd">新增</el-button>
                                </div>
                            </div>
                            <el-table :data="presetData" height="300" style="width: 100%" size="mini"
                                :cell-style="{ color: '#333' }">
                                <el-table-column prop="name" label="预置位名称" show-overflow-tooltip="" />
                                <el-table-column prop="groupName" label="分组名称" show-overflow-tooltip="" />
                                <el-table-column label="操作" align="center" width="140" fixed="right">
                                    <template v-slot="{ row }">
                                        <el-button class="text-btn-table" type="text" size="mini"
                                            @click="handleOrientation(row)">定位</el-button>
                                        <el-button class="text-btn-table" type="text" size="mini"
                                            @click="handleEdit(row)">编辑</el-button>
                                        <el-button class="text-btn-table" type="text" size="mini"
                                            @click="handleDelete(row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-card>
                    </el-col>
                </el-row>

                <!-- 新增or修改预置位 -->
                <el-dialog :title="dialogTitle" :show-close="false" @close="cancel" :visible.sync="dialogVisible"
                    width="560px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
                    <el-form :model="model" ref="planForm" :rules="rules" label-width="140px" class="form">
                        <el-row :gutter="10">
                            <el-col :span="24">
                                <el-form-item label="预置位名称：" prop="name">
                                    <el-input size="mini" clearable v-model="model.name" placeholder="请输入预置位名称"
                                        style="width: 100%;"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="机器人位置：" prop="robotPresetPosition">
                                    <el-select size="mini" v-model="model.robotPresetPosition" placeholder="请选择机器人位置"
                                        style="width: 100%;">
                                        <el-option :label="item" :value="item" :key="item"
                                            v-for="item in robotPresetPositionList" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="分组名称：" prop="groupName">
                                    <el-input size="mini" clearable v-model="model.groupName" placeholder="请输入预置位名称"
                                        style="width: 100%;"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="cancel">取 消</el-button>
                        <el-button type="primary" @click="ok">确 定</el-button>
                    </span>
                </el-dialog>
            </div>
        </div>
    </div>
</template>
<script>
import { getMachineRoom } from "@/api/computerRoomApi.js";
import { detailRobotSetting, robotPresetSetting, robotPresetDelete, robotOperate, presetList, robotPresetUpdate, orientation, robotStatus } from "@/api/rabotManageApi.js";
import monitorVideo from "@/components/monitorVideo.vue";
export default {
    data() {
        return {
            form: {
                resourceId: '',
            },
            configData: {},
            selecData: [],
            robotPresetPositionList: [],
            offsetWidth: 0,
            dialogVisible: false,
            dialogTitle: "新增预置位",
            model: {
                name: "",
                robotPresetPosition: 1,
                robotNumber: "",
                groupName: "",
            },
            rules: {
                name: [
                    { required: true, message: "请输入预置位名称", trigger: "blur" },
                ],
                groupName: [
                    { required: true, message: "请输入分组名称", trigger: "blur" },
                ],
            },
            presetData: [],
            robotStatusData: {},
            timer: null
        };
    },
    components: { monitorVideo },
    watch: {
        dialogVisible(val) {
            if (val) {
                this.$refs.monitorVideoRef.hidPlugin();
            } else {
                this.$refs.monitorVideoRef.showPlugin();
            }
        }
    },
    mounted() {
        this.robotPresetPositionList = Array(255).fill("");
        this.robotPresetPositionList.forEach((_, index) => { this.robotPresetPositionList[index] = index + 1 });
        this.offsetWidth = this.$refs.videoHome.$el.offsetWidth - 20;
        this.getMachineRoomData();
        this.getMessageData();
    },
    beforeDestroy() {
        this.$refs.monitorVideoRef.destroyPlugin();
        clearInterval(this.timer);
        this.timer = null;
    },
    methods: {
        getPresetData() {
            presetList({ robotNumber: this.configData.robotNumber }).then(res => {
                if (res.code == 200) {
                    this.presetData = res.info;
                } else {
                    this.$message({
                        message: res.msg,
                        type: "error",
                    })
                    this.presetData = [];
                }
            })
        },
        handleResourceChange() {
            this.$refs.monitorVideoRef.destroyPlugin();
            this.getRobotConfig();
        },
        getRobotConfig() {
            if (!this.$route.query.robotNumber) {
                return this.$message({
                    message: "该机房没有绑定机器人",
                    type: "warning",
                })
            }
            detailRobotSetting(this.$route.query.robotNumber).then(res => {
                if (res.code == 200) {
                    this.configData = { ...res.info, cameraPort: 80 };
                    this.getPresetData();
                    this.$nextTick(() => {
                        this.$refs.monitorVideoRef.initPlugin()
                    })
                } else {
                    this.configData = {}
                }
            })
        },
        getMachineRoomData() {
            getMachineRoom().then(res => {
                if (res.code == "200") {
                    this.selecData = res.info;
                    this.form.resourceId = this.$route.query.resourceId;
                    this.getRobotConfig();
                }
            });
        },
        handleFocus() {
            this.$refs.monitorVideoRef.hidPlugin();
        },
        handleBlur() {
            this.$refs.monitorVideoRef.showPlugin();
        },
        async mouseDownPTZControl(type) {
            const res = await robotStatus(this.$route.query.robotNumber)
            if (res.code == 200 && res.info.status) {
                return this.$message({
                    message: "机器人正在执行巡检任务，无法操作",
                    type: "warning",
                })
            }
            switch (type) {
                case 1:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(1);
                    break;
                case 2:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(7);
                    break;
                case 3:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(4);
                    break;
                case 4:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(8);
                    break;
                case 5:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(2);
                    break;
                case 6:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(6);
                    break;
                case 7:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(3);
                    break;
                case 8:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(5);
                    break;
                case 9:
                    this.$refs.monitorVideoRef.mouseDownPTZControl(9);
                    break;
            }
        },
        async mouseUpPTZControl() {
            const res = await robotStatus(this.$route.query.robotNumber)
            if (res.code == 200 && res.info.status) {
                return this.$message({
                    message: "机器人正在执行巡检任务，无法操作",
                    type: "warning",
                })
            }
            this.$refs.monitorVideoRef.mouseUpPTZControl();
        },
        async handleKeyDown(item) {
            const res = await robotStatus(this.$route.query.robotNumber)
            if (res.code == 200 && res.info.status) {
                return this.$message({
                    message: "机器人正在执行巡检任务，无法操作",
                    type: "warning",
                })
            }
            switch (item) {
                case 1:
                    this.handleOperation('upStart');
                    break;
                case 2:
                    this.handleOperation('rightStart');
                    break;
                case 3:
                    this.handleOperation('downStart');
                    break;
                case 4:
                    this.handleOperation('leftStart');
                    break;
            }
        },
        async handleKeyUp(item) {
            const res = await robotStatus(this.$route.query.robotNumber)
            if (res.code == 200 && res.info.status) {
                return this.$message({
                    message: "机器人正在执行巡检任务，无法操作",
                    type: "warning",
                })
            }
            switch (item) {
                case 1:
                    this.handleOperation('upStop');
                    break;
                case 2:
                    this.handleOperation('rightStop');
                    break;
                case 3:
                    this.handleOperation('downStop');
                    break;
                case 4:
                    this.handleOperation('leftStop');
                    break;
            }
        },
        goBack() {
            this.$refs.monitorVideoRef.destroyPlugin();
            this.$router.go(-1)
        },
        cancel() {
            this.model = {
                name: "",
                robotPresetPosition: 1,
                robotNumber: "",
                groupName: "",
            };
            this.$refs.planForm.clearValidate();
            this.dialogVisible = false;
        },
        ok() {
            this.$refs.planForm.validate(async valid => {
                if (valid) {
                    const res = await robotStatus(this.$route.query.robotNumber)
                    if (res.code == 200 && res.info.status) {
                        return this.$message({
                            message: "机器人正在执行巡检任务，无法操作",
                            type: "warning",
                        })
                    }
                    if (this.dialogTitle == "新增预置位") {
                        robotPresetSetting({
                            ...this.model,
                            cameraPresetPosition: this.model.robotPresetPosition,
                            robotNumber: this.configData.robotNumber
                        }).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    message: "添加成功",
                                    type: "success",
                                });
                                this.getPresetData();
                                this.cancel();
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error",
                                });
                            }
                        })
                    } else {
                        robotPresetUpdate({
                            ...this.model,
                            cameraPresetPosition: this.model.robotPresetPosition,
                            robotNumber: this.configData.robotNumber
                        }).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    message: "修改成功",
                                    type: "success",
                                });
                                this.getPresetData();
                                this.cancel();
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error",
                                });
                            }
                        })
                    }
                }
            })
        },
        async handleOrientation(row) {
            const res = await robotStatus(this.$route.query.robotNumber)
            if (res.code == 200 && res.info.status) {
                return this.$message({
                    message: "机器人正在执行巡检任务，无法操作",
                    type: "warning",
                })
            }
            orientation({
                robotNumber: this.configData.robotNumber,
                presetId: row.id,
            }).then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: "正在执行定位，请稍等",
                        type: "success",
                    });
                } else {
                    this.$message({
                        message: res.msg,
                        type: "error",
                    });
                }
            })
        },
        async handleAdd() {
            const res = await robotStatus(this.$route.query.robotNumber)
            if (res.code == 200 && res.info.status) {
                return this.$message({
                    message: "机器人正在执行巡检任务，无法操作",
                    type: "warning",
                })
            }
            this.dialogVisible = true;
            this.dialogTitle = '新增预置位'
        },
        async handleEdit(row) {
            const res = await robotStatus(this.$route.query.robotNumber)
            if (res.code == 200 && res.info.status) {
                return this.$message({
                    message: "机器人正在执行巡检任务，无法操作",
                    type: "warning",
                })
            }
            this.dialogTitle = "编辑预置位";
            this.model = { ...row };
            this.dialogVisible = true;
        },
        async handleDelete(row) {
            const res = await robotStatus(this.$route.query.robotNumber)
            if (res.code == 200 && res.info.status) {
                return this.$message({
                    message: "机器人正在执行巡检任务，无法操作",
                    type: "warning",
                })
            }
            robotPresetDelete(row.id).then((res) => {
                if (res.code == 200) {
                    this.$message({
                        message: "删除成功",
                        type: "success",
                    });
                    this.getPresetData();
                } else {
                    this.$message({
                        message: res.msg,
                        type: "error",
                    });
                }
            });
        },
        handleOperation(type) {
            robotOperate({
                robotNumber: this.configData.robotNumber,
                order: type,
            }).then((res) => {
                if (res.code == 200) {
                    this.$message({
                        message: "操作成功",
                        type: "success",
                    });
                } else {
                    this.$message({
                        message: res.msg,
                        type: "error",
                    });
                }
            })
        },
        getMessageData() {
            robotStatus(this.$route.query.robotNumber).then(res => {
                if (res.code == 200) {
                    this.robotStatusData = res.info;
                } else {
                    this.robotStatusData = null
                }
            })
            this.timer = setInterval(() => {
                robotStatus(this.$route.query.robotNumber).then(res => {
                    if (res.code == 200) {
                        this.robotStatusData = res.info;
                    } else {
                        this.robotStatusData = null
                    }
                })
            }, 60000);
        }
    },
};
</script>
<style lang="scss" scoped>
.main {
    width: 100%;
    height: 100%;
    overflow: auto;
    margin: 0 auto;

    .head-wrap {
        padding: 20px 17px;
        border-radius: 6px;

        /deep/ .el-form-item {
            margin-bottom: 0;

            .el-form-item__label {
                color: #000;
            }
        }
    }

    .head-wrap,
    .bottom-wrap {
        background: #ffffff;
        box-shadow: 0px 0px 12px 0px rgba(129, 155, 151, 0.3);
    }

    .bottom-wrap {
        padding: 0 15px;
        border-radius: 10px;
        height: 89%;
        overflow: hidden;

        .table-wrap {
            height: 100%;
            overflow: auto;
            color: #333;
        }
    }
}

.mt15 {
    margin-top: 15px;
}

.flex {
    display: flex;
}

.flex-jsb {
    display: flex;
    justify-content: space-between;
}

.circle {
    /* 设置圆环的样式 */
    width: 140px;
    height: 140px;
    margin: auto;
    border: 8px solid #5e686f;
    background-color: #838a90;
    border-radius: 50%;

    .inner-circle {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        position: relative;
    }

    /* 8个箭头分布在圆环内 */
    .inner-circle i {
        position: absolute;
        font-size: 26px;
        color: #fff;
        transform-origin: center;
        cursor: pointer;
    }

    .inner-circle-1 {
        top: 10%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    .inner-circle-2 {
        top: 25%;
        left: 75%;
        transform: translate(-50%, -50%) rotate(45deg);
    }

    .inner-circle-3 {
        top: 50%;
        left: 90%;
        transform: translate(-50%, -50%) rotate(-270deg);
    }

    .inner-circle-4 {
        top: 75%;
        left: 75%;
        transform: translate(-50%, -50%) rotate(-225deg);
    }

    .inner-circle-5 {
        top: 90%;
        left: 50%;
        transform: translate(-50%, -50%) rotate(-180deg);
    }

    .inner-circle-6 {
        top: 75%;
        left: 25%;
        transform: translate(-50%, -50%) rotate(-135deg);
    }

    .inner-circle-7 {
        top: 50%;
        left: 10%;
        transform: translate(-50%, -50%) rotate(-90deg);
    }

    .inner-circle-8 {
        top: 25%;
        left: 25%;
        transform: translate(-50%, -50%) rotate(-45deg);
    }
}


.circle2 {
    /* 设置圆环的样式 */
    width: 120px;
    height: 120px;
    margin: auto;
    border: 8px solid #5e686f;
    background-color: #838a90;
    border-radius: 50%;

    .inner-circle {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        position: relative;
    }

    /* 8个箭头分布在圆环内 */
    .inner-circle i {
        position: absolute;
        font-size: 40px;
        color: #fff;
        transform-origin: center;
        cursor: pointer;
    }

    .inner-circle-1 {
        top: 10%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    .inner-circle-2 {
        top: 50%;
        left: 90%;
        transform: translate(-50%, -50%) rotate(-270deg);
    }

    .inner-circle-3 {
        top: 90%;
        left: 50%;
        transform: translate(-50%, -50%) rotate(-180deg);
    }

    .inner-circle-4 {
        top: 50%;
        left: 10%;
        transform: translate(-50%, -50%) rotate(-90deg);
    }
}

.inner-btn {
    width: 60px;
    height: 60px;
    border: 6px solid #409eff;
    border-radius: 50%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
}

.el-icon-refresh {
    color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.robot-control {
    .robot-control-item {
        display: flex;
        align-items: center;
        margin-top: 10px;

        span {
            display: inline-block;
            width: 50px;
        }
    }
}
</style>
